import json
import os
import requests
import re

def sanitize_filename(filename):
    # 移除不合法的文件名字符
    return re.sub(r'[<>:"/\\|?*]', '', filename)

def process_json_file(json_file, output_folder):
    # 读取JSON文件
    with open(json_file, 'r', encoding='utf-8') as f:
        data = json.load(f)

    # 处理每个条目
    for item in data:
        # 获取标题和URL
        if 'display_title' not in item:
            continue
            
        title = item['display_title']
        if 'cover' not in item or 'info_list' not in item['cover'] or not item['cover']['info_list']:
            continue
            
        url = item['cover']['info_list'][0]['url']
        
        # 创建安全的文件夹名
        safe_title = sanitize_filename(title)
        folder_path = os.path.join(output_folder, safe_title)
        
        # 创建文件夹
        os.makedirs(folder_path, exist_ok=True)
        
        # 创建并写入文本文件
        text_data = {
            'title': title,
            'url': url
        }
        with open(os.path.join(folder_path, '文本'), 'w', encoding='utf-8') as f:
            json.dump(text_data, f, ensure_ascii=False, indent=2)
        
        # 下载图片
        try:
            response = requests.get(url)
            if response.status_code == 200:
                with open(os.path.join(folder_path, 'Image.jpg'), 'wb') as f:
                    f.write(response.content)
                print(f'Successfully processed: {title}')
            else:
                print(f'Failed to download image for: {title}')
        except Exception as e:
            print(f'Error processing {title}: {str(e)}')

# 处理所有JSON文件
json_files = ['1.json', '2.json', '3.json', '4.json', '5.json', '6.json']
for json_file in json_files:
    output_folder = f'@{json_file.split(".")[0]}'
    print(f'\nProcessing {json_file} into {output_folder}...')
    process_json_file(json_file, output_folder) 